package com.betterwood.dragon.worms;

import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.TimeUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DZ {

    // 大众可用
    public static String login(Site site) {
        log.info("#########################################");
        log.info("############START LOGIN TO DZ############");
        String contextState = "EMPTY";

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();

            // Open new page
            Page page = context.newPage();

            // Go to http://www.fuji-pharm.cn/
            // page.navigate(site.getSiteUrl());
            page.navigate("https://www.jzqyyw.com/gzmpc/zh/CNY/");
            page.click("text=登 录");
            // assert page.url().equals("https://www.jzqyyw.com/login");
            // Click [placeholder="手机号 / 操作码 / 邮箱"]
            page.click("#j_username");
            // Fill [placeholder="手机号 / 操作码 / 邮箱"]
            page.fill("#j_username", site.getUserName());
            // Click [placeholder="请输入密码"]
            page.click("#j_password");
            // Fill [placeholder="请输入密码"]
            page.fill("#j_password", site.getPassWord());
            // Check input[name="remember-me"]
            page.check("input[name=\"remember-me\"]");
            // Click text=登 录

            page.waitForNavigation(() -> {
                page.click("text=登 录");
            });

            contextState = context.storageState();
            // log.info(contextState);
            log.info("############END OF LOGIN TO DZ#############");

        } catch (RuntimeException e) {
            e.printStackTrace();

        }
        return contextState;
    }

    public static List<Result> fetchProduct(Site site, SearchDTO search) {
        log.info("#######################################");
        log.info("############START FETCH FROM DZ########");

        List<Result> initList = new ArrayList<>();
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));

            String storageState = site.getLoginInfo();

            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageState(storageState));
            context.setDefaultTimeout(60000);

            // Open new page
            Page page = context.newPage();
            page.navigate(site.getSiteUrl());
            log.info("**********");
            log.info(search.getKeywordStr());
            log.info("**********");

            if (page.isVisible("div:nth-child(100) .dialog-adv-content .delelte-dialog-adv img",
                    new Page.IsVisibleOptions().setTimeout(3200))) {
                // log.info("HERE IS THE ADV DELETE");
                page.click("div:nth-child(100) .dialog-adv-content .delelte-dialog-adv img");

            } else {
                // log.info("HERE IS NO ADV DELETE");

            }

            page.click("#js-site-search-input");
            page.fill("#js-site-search-input", search.getKeywordStr());
            page.waitForNavigation(() -> {
                page.click(".js_search_button");
            });

            page.waitForTimeout(1500);
            if (!page.isVisible(".product__grid")) {
                log.info("DZ HAVE NO RESULTS");
                return initList;
            }

            String content = page.innerHTML(".product__grid");
            initList = getList(content, search, site);

            if (!page.isVisible(".pagination")) {
                log.info("**************DZ FOUND NEW PRODUCTS!!!******************");
                log.info(Integer.toString(initList.size()));
                log.info("DZ HAVE ONLY ONE PAGE");
                log.info("**************DZ FOUND NEW PRODUCTS!!!******************");
                return initList;
            }

            String pager = page.innerHTML(".pagination");
            // log.info(pager);

            Document pagerDoc = Jsoup.parseBodyFragment(pager);

            // Elements rightArrows = pagerDoc.getElementsByClass("pagination-next");
            // log.info(Integer.toString(rightArrows.size()));
            Element rightArrow = pagerDoc.getElementsByClass("pagination-next").first();
            // log.info(rightArrow.classNames().toString());
            boolean hasNext = !rightArrow.classNames().contains("disabled");
            // boolean hasNext = false;

            page.waitForTimeout(1500);

            List<Result> otherList = new ArrayList<>();
            while (hasNext) {
                page.click(".pagination-next");
                page.waitForTimeout(2500);

                content = page.innerHTML(".product__grid");

                pager = page.innerHTML(".pagination");

                pagerDoc = Jsoup.parseBodyFragment(pager);
                otherList = getList(content, search, site);
                initList.addAll(otherList);

                rightArrow = pagerDoc.getElementsByClass("pagination-next").first();
                hasNext = !rightArrow.classNames().contains("disabled");
            }

        } catch (RuntimeException e) {
            e.printStackTrace();
            log.info("DZ WORM FAILED");
        }

        log.info("**************DZ FOUND NEW PRODUCTS!!!******************");
        log.info(Integer.toString(initList.size()));
        log.info("**************DZ FOUND NEW PRODUCTS!!!******************");
        return initList;
    }

    public static List<Result> getList(String content, SearchDTO search, Site site) {

        List<Result> list = new ArrayList<>();

        Document doc = Jsoup.parseBodyFragment(content);
        Element body = doc.body();

        Elements lis = body.getElementsByClass("product-item");

        if (lis.size() == 0) {
            log.info("DZ HAVE NO RESULTS");
            return list;
        }

        for (Element li : lis) {
            // log.info("***************************************************");
            // Element info = li.getElementsByClass("js-product-info").first();
            // String pName = li.getElementsByClass("js-productName").first().text();
            Elements els = li.getElementsByClass("name");
            String pName = els.first().text();
            String orderUrl = els.first().attributes().get("href");
            // log.info("商品名是:" + pName);
            String sourcePrice = li.getElementsByClass("carousel__item--price").first().text();
            String sourcePriceClean = StrUtil.removePrefix(sourcePrice, "¥");
            // log.info("价格是:" + sourcePriceClean);
            // String amountLeft = li.getElementsByClass("flex_hei").first().text();

            Double priceDouble = NumberUtil.isNumber(sourcePriceClean) ? Double.parseDouble(sourcePriceClean) : 0;
            // log.info("数字价格是:" + priceDouble.toString());

            // log.info("剩余数量是:" + amountLeft);
            // String sourceCode = li.getElementsByClass("flex_p").get(1).text();
            // String sourceCodeClean = StrUtil.split(sourceCode, "：")[1];
            // log.info("商品编码是:" + sourceCodeClean);

            // String sourcePropClean = StrUtil.split(sourceProp, "：")[1];
            String sourcePropClean = li.getElementsByClass("carousel__item--specification").first().text();
            // log.info("商品规格是:" + sourcePropClean);
            String sourceProducer = li.getElementsByClass("carousel__item--company").first().text();

            // log.info("商品制造厂是:" + sourceProducer);

            // log.info("商品购买URL是:" + orderUrl);

            // String partnerCode = site.getSiteNo() + sourceCodeClean;

            Result re = new Result();
            re.setKeywordStr(search.getKeywordStr());
            re.setProductName(StrUtil.concat(true, pName, ":", sourcePropClean, ":", sourceProducer));
            re.setOrderUrl(StrUtil.concat(true, site.getSiteUrl(), orderUrl));
            re.setProp(sourcePropClean);
            re.setMaker(sourceProducer);
            re.setScanTime(TimeUtil.currentTime());

            re.setSearchId(search.getId());
            re.setSiteName("大众");
            // // re.setSiteId("");
            re.setSiteNo("DZ");
            re.setScanPrice(sourcePriceClean);

            re.setPrice(priceDouble);
            re.setStatus(0);

            list.add(re);

        }

        return list;
    }
}
